package Servlets.xzh;

import Bean.Product;
import Bean.User;
import Bean.UserIndex.Order;
import Bean.UserIndex.ShoppingList;
import Util.GokJDBCUtil2;
import Util.RES;
import Util.SimpleOrderCodeGenerator;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;


@Slf4j
@WebServlet(name = "ShoppingToOrderServlet", urlPatterns = "/ShoppingToOrderServlet")
public class ShoppingToOrderServlet extends HttpServlet {
    public void init() {
    }

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
        User user =(User) req.getSession().getAttribute("user");
        int user_id = user.getId();
        ShoppingList cart = JSON.parseObject(req.getParameter("cart"), ShoppingList.class);
        String code = SimpleOrderCodeGenerator.generateOrderCode();
        BigDecimal totalamount = BigDecimal.ZERO; // 确保是有效 BigDecimal 对象
        StringBuilder remark = new StringBuilder();
        for (Product product: cart.getCarts()){
            BigDecimal price = product.getPrice(); // BigDecimal 类型
            Integer quantity = product.getQuantity(); // Integer 类型
            totalamount = totalamount.add(price.multiply(BigDecimal.valueOf(quantity)));
            remark.append(product.getProname()+" ");

        }
        remark.append("购买");
        String sql = "insert into sales_order (code,userid,ordertime,totalamount,paymentstatus,orderstatus,remark,isdeleted) values (?,?,now(),?,?,?,?,?)";
        int update = GokJDBCUtil2.update(sql, code, user_id, totalamount, 0, 0,remark.toString(), 0);
        if (update>0){
            String sql_findid = "select id from sales_order where code=?";
            Order order = GokJDBCUtil2.queryForObject(sql_findid, Order.class, code);
            int id =  order.getId();
            for (Product product: cart.getCarts()){
                //减少库存
                String sql_stock = "select quantity from product where id=?";
                Product product1 = GokJDBCUtil2.queryForObject(sql_stock, Product.class, product.getId());
                if(product1.getQuantity()<product.getQuantity()){
                    //库存不足
                    PrintWriter writer = res.getWriter();
                    writer.print(RES.fail("库存不足"));
                    writer.close();
                    return;
                }
                int stock = 0;
                if (product1 != null) {
                    stock = product1.getQuantity()-product.getQuantity();
                }

                //提交订单
                String stock_update = "update product set quantity=? where id=?";
                GokJDBCUtil2.update(stock_update,stock,product.getId());
                String sql_insert_detail = "insert into sales_order_detail (orderid,proid,number,proquantity,unitprice,createtime,isdeleted) " +
                        " values (?,?,?,?,?,now(),?)";
                GokJDBCUtil2.update(sql_insert_detail,id,product.getId(),product.getQuantity(),product.getQuantity(),product.getPrice(),0);
                String sql_income = "insert into income (code,money,incometime,paymentmethod,remark,createtime,updatetime,isdeleted) "+
                        " values (?,?,now(),?,?,now(),now(),?)";
                BigDecimal price = product.getPrice(); // BigDecimal 类型
                Integer quantity = product.getQuantity(); // Integer 类型
                BigDecimal money = BigDecimal.ZERO;
                money = money.add(price.multiply(BigDecimal.valueOf(quantity)));
                GokJDBCUtil2.update(sql_income,code,money,"支付宝",product.getProname(),0);
            }
            PrintWriter writer = res.getWriter();
            writer.print(RES.success("购买成功"));
            writer.close();
        }else{
            PrintWriter writer = res.getWriter();
            writer.print(RES.fail("购买失败"));
            writer.close();
        }


    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String method = req.getMethod();
        try {
            if (method.equals("GET")) {
                this.doGet(req, res);
            }else if(method.equals("POST")){
                this.doGet(req, res);
            }else {
                PrintWriter writer = res.getWriter();
                writer.println("{\"code\":\"400\",\"msg\":\"此方法不允许\"}");
                writer.close();
            }
        } catch (Exception e) {
            log.error("服务器处理请求时发生错误", e);
            PrintWriter writer = res.getWriter();
            writer.println("{\"code\":\"500\",\"msg\":\"服务器处理请求时发生错误\"}");
            writer.close();
        }
    }
    public void destroy() {
    }
}